package com.begamer.card.common.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * 
 * @ClassName: RequestDiagnosticFilter
 * @Description: TODO 页面响应时间过滤器
 * @author gs
 * @date Nov 10, 2011 4:07:39 PM
 * 
 */

public class RequestDiagnosticFilter implements Filter {
	private Logger log = Logger.getLogger(RequestDiagnosticFilter.class);

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		long t1 = System.currentTimeMillis();
		HttpServletRequest req = (HttpServletRequest) request;

		String requri = req.getRequestURI();

		log.warn("\n\n\n*** Diagnosis begin: " + requri);
		log
				.info("================================================================================================================");

		String[] str = requri.split("/");
		if (str.length == 5) {
			String MiscID = str[3] + "/";
			log.debug("MiscID:" + MiscID);
		}

		log.info("\r\n\t" + req.getRemoteAddr() + ":" + req.getRemotePort()
				+ " " + req.getMethod() + " - " + req.getRequestURI() + "?"
				+ req.getQueryString());

		String name = "";
		String val = "";

		Enumeration headers = req.getHeaderNames();
		while (headers.hasMoreElements()) {
			name = (String) headers.nextElement();
			val = req.getHeader(name);

			log.info("\tHEAD " + name + " : " + val);
		}
		// String temp = req.getHeader("user-agent");
		// log.info("user-agent,haha:" + temp);
		Enumeration params = req.getParameterNames();
		while (params.hasMoreElements()) {
			name = (String) params.nextElement();
			val = req.getParameter(name);
			if (val == null)
				val = "null";
			log.info("\tPARAM " + name + " : " + val + ":length:"
					+ val.length());
		}

		Enumeration attributes = req.getSession().getAttributeNames();
		while (attributes.hasMoreElements()) {
			name = (String) attributes.nextElement();
			Object obj = req.getSession().getAttribute(name);

			log.info("\tSESSION " + name + " : " + obj);
		}

		log
				.info("\n----------------------------------------------------------------------------------------------------------------");
		chain.doFilter(request, response);

		log
				.info("================================================================================================================");
		log.warn("*** Diagnosis ends: " + requri + " USED : "
				+ (System.currentTimeMillis() - t1) + "ms\n\n\n");

	}

	public void destroy() {
	}
}